﻿using System;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace CRM.Extensions
{
    public static class StringExtension
    {
        /// <summary>
        /// 创建固定hashcode
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static long GetFixedHashCode(this string str)
        {
            var md5 = System.Security.Cryptography.MD5.Create();
            md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(str));
            var hash = md5.Hash;
            var temp = new byte[8];
            Array.Copy(hash.Reverse().ToArray(), 4, temp, 0, 7);
            var b4 = (byte)(hash[4] >> 1);
            //b4 &= 0x7F;
            temp[7] = b4;
            return BitConverter.ToInt64(temp);
        }

        public static JObject FileToJson(this string path)
        {
            using var stream = new StreamReader(path);
            using var jsonReader = new JsonTextReader(stream);
            return JObject.Load(jsonReader);
        }
        
        public static void WriteTo(this JObject json, string path, Formatting formatting = Formatting.Indented)
        {
            using var writer = new StreamWriter(path);
            using var jsonWriter = new JsonTextWriter(writer);
            jsonWriter.Formatting = formatting;
            json.WriteTo(jsonWriter);
        }
    }
}